﻿using RunUI.SysModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RunUI.AspNetCore
{
    internal class DefaultForeignEnumProvider : IForeignEnumProvider
    {
        readonly IFreeSql orm;
        readonly ITenantProvider tenantProvider;
        public DefaultForeignEnumProvider(IFreeSql freeSql, ITenantProvider tenantProvider)
        {
            orm = freeSql;
            this.tenantProvider = tenantProvider;

        }

        public async Task<List<TreeNode>> GetEnumTreeNodeAsync(string code)
        {
            string tenantId = null;


            if (tenantProvider != null)
            {
                tenantId = await tenantProvider.GetTenantId();
            }
            var list = await orm.Select<TSysEnum, TSysEnumItem>()
                 .WhereIf(tenantId.HasValue(), e => e.t1.TenantId == tenantId)
                 .Where((e, ei) => e.Name == code && e.Id == ei.SysEnumId)
                 .ToListAsync((e, ei) => new
                 {
                     ei.Id,
                     ei.Name,
                     ei.SortId,
                     ei.ParentId,
                     ei.Description
                 });

            var treeNodeItems = list.Select(i => new TreeNodeItem
            {
                Id = i.Id,
                Extra = new Dictionary<string, object> { { "Description", i.Description } },
                Name = i.Name,
                ParentId = i.ParentId,
                Weight = i.SortId
            }).ToList();
            var treeNodes = TreeNodeHelper.Make(treeNodeItems, null);

            return treeNodes;
        }


        public async Task<List<LabelValue>> GetEnumValuesAsync(string code)
        {
            string tenantId = null;


            if (tenantProvider != null)
            {
                tenantId = await tenantProvider.GetTenantId();
            }
            var list = await orm.Select<TSysEnum, TSysEnumItem>()
                 .WhereIf(tenantId.HasValue(), e => e.t1.TenantId == tenantId)
                 .Where((e, ei) => e.Name == code && e.Id == ei.SysEnumId)
                 .ToListAsync((e, ei) => new LabelValue
                 {
                     Value = ei.Id,
                     Label = ei.Name,
                 });

            return list;
        }
    }
}
